package se.kth.fericss.rts;

import java.util.Random;
import java.awt.geom.Point2D;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

public class TileMap {
	@SuppressWarnings("unused")
	private Game 	game;
	private Tile 	sprite;
	private Image	cachedImage;
	@SuppressWarnings("unused")
	private World 	world;
	private View 	worldView;
	private Tile list[][];
	
	public TileMap(Game game, World world, View worldView){
		this.game= 		game;
		this.world= 	world;
		this.worldView=	worldView;
		try {
			try {
				sprite = new Tile(Game.IMAGE_PATH + "groundTile1.png");
			} catch(SlickException ex) {
				System.out.println("Could not load image groundTile.png");
				ex.printStackTrace();
			}
			cachedImage = new Image(world.getWidth() + sprite.getWidth() * 2, world.getHeight() + sprite.getHeight() * 2);
			Graphics g = cachedImage.getGraphics();

			int numTilesX = world.getWidth() / sprite.getWidth() + 4;
			int numTilesY = world.getHeight() / sprite.getHeight() + 4;
			list= new Tile[numTilesX][numTilesY];
			
			
			for(int yPos = 0; yPos < numTilesY; yPos++) {
				for(int xPos = 0; xPos < numTilesX; xPos++) {
					try {
						sprite = new Tile(Game.IMAGE_PATH + "groundTile"+(int)(Math.random()*3+1)+".png");
						list[xPos][yPos]=sprite;
					} catch(SlickException ex) {
						System.out.println("Could not load image groundTile.png");
						ex.printStackTrace();
					}
					g.drawImage(sprite, xPos * sprite.getWidth(), yPos * sprite.getHeight());
				}
			}

			g.flush();
		} catch(SlickException ex) {
			System.out.println("Could not create image for drawing tiles.");
			ex.printStackTrace();
		}
	}
	public void draw(Graphics g) {
		Point2D.Float viewLocation = worldView.getCurrentViewLocation();
		float tileOffsetX = -viewLocation.x % sprite.getWidth();
		float startX = -viewLocation.x - tileOffsetX - sprite.getWidth();
		float tileOffsetY = -viewLocation.y % sprite.getHeight();
		float startY = -viewLocation.y - tileOffsetY - sprite.getHeight();
		g.drawImage(cachedImage, 0, 0);
	}
}
